package com.sadam.ui4.FragmentSelfPage;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentCommentPage.FragmentCommentPage;
import com.sadam.ui4.FragmentHomePage.VideoAdapter;
import com.sadam.ui4.FragmentHomePage.VideoViewHolder;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;
import com.sadam.ui4.Utils.NoScrollLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

public class FragmentPersonalVideoPlayer extends DialogFragment {

    private static final String TAG = "FragmentPersonalVideoPlayer";
    private static final String ARG_VIDEOS = "videos";
    private static final String ARG_START_POSITION = "startPosition";
    private static final String ARG_ENABLE_SWIPE = "enableSwipe";

    private RecyclerView recyclerView;
    private ImageButton btnClose;
    private VideoAdapter videoAdapter;
    private List<Video> videoList = new ArrayList<>();
    private int startPosition;
    private MySqLiteOpenHelper dbHelper;
    private MainActivity mainActivity;
    private boolean enableSwipe = true;

    public FragmentPersonalVideoPlayer() {
        // Required empty public constructor
    }

    /**
     * 创建新的实例 - 向后兼容版本（默认启用滑动）
     */
    public static FragmentPersonalVideoPlayer newInstance(List<Video> videoList, int startPosition) {
        return newInstance(videoList, startPosition, true);
    }

    public static FragmentPersonalVideoPlayer newInstance(List<Video> videos, int startPosition, boolean enableSwipe) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_VIDEOS, new ArrayList<>(videos));
        args.putInt(ARG_START_POSITION, startPosition);
        args.putBoolean(ARG_ENABLE_SWIPE, enableSwipe);

        FragmentPersonalVideoPlayer fragment = new FragmentPersonalVideoPlayer();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mainActivity = (MainActivity) context;
            dbHelper = mainActivity.getMySqLiteOpenHelper();
        } else {
            throw new RuntimeException("FragmentPersonalVideoPlayer 必须依附于 MainActivity");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle);

        if (getArguments() != null) {
            ArrayList<Video> videos = (ArrayList<Video>) getArguments().getSerializable(ARG_VIDEOS);
            startPosition = getArguments().getInt(ARG_START_POSITION, 0);
            enableSwipe = getArguments().getBoolean(ARG_ENABLE_SWIPE, true);

            if (videos != null) {
                videoList = videos;
            } else {
                videoList = new ArrayList<>();
            }
        }
    }

    /**
     * 加载视频方法，返回加载的视频列表
     */
    private List<Video> loadVideosByIds(List<Long> videoIds) {
        List<Video> loadedVideos = new ArrayList<>();

        try {
            List<Video> allVideos = dbHelper.getAllVideos();

            for (Long videoId : videoIds) {
                for (Video video : allVideos) {
                    if (video.getId() == videoId) {
                        loadedVideos.add(video);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            Toast.makeText(getContext(), "加载视频失败", Toast.LENGTH_SHORT).show();
        }
        return loadedVideos;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_video_player, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.recyclerview_video_player);
        btnClose = view.findViewById(R.id.btn_close_player);

        // 初始化适配器
        videoAdapter = new VideoAdapter(mainActivity, dbHelper) {
            @Override
            public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
                Video video = getVideos().get(position);

                User currentUser = User.getCurrentUser(mainActivity, dbHelper);
                if (currentUser == null) {
                    Toast.makeText(mainActivity, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }

                holder.bind(video, dbHelper, currentUser);

                holder.commentButton.setOnClickListener(v -> {
                    if (video == null) return;

                    FragmentCommentPage dialog = FragmentCommentPage.newInstance(video.getId());

                    // 设置评论对话框关闭时的回调
                    dialog.setOnCommentPostedListener(() -> {
                        // 评论发布后刷新当前播放器的视频数据
                        refreshVideoData();

                        // 同时通知MainActivity刷新其他页面
                        if (mainActivity != null) {
                            mainActivity.refreshHomePage();
                            mainActivity.refreshMessageAndSelfPages();
                        }
                    });

                    dialog.show(mainActivity.getSupportFragmentManager(), "comment_dialog");
                });
            }
        };

        // 关键修改：根据视频数量和滑动设置来决定布局管理器
        if (enableSwipe && videoList.size() > 1) {
            // 多视频 + 启用滑动：使用正常的LinearLayoutManager + PagerSnapHelper
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
            pagerSnapHelper.attachToRecyclerView(recyclerView);
        } else {
            // 单视频 或 禁用滑动：使用特殊的NoScrollLinearLayoutManager
            recyclerView.setLayoutManager(new NoScrollLinearLayoutManager(getContext()));
        }

        recyclerView.setAdapter(videoAdapter);

        // 设置视频数据
        if (!videoList.isEmpty()) {
            videoAdapter.setVideos(videoList);

            recyclerView.post(() -> {
                if (startPosition >= 0 && startPosition < videoList.size()) {
                    recyclerView.scrollToPosition(startPosition);
                }
            });
        }

        btnClose.setOnClickListener(v -> dismiss());
    }

    @Override
    public void onStart() {
        super.onStart();
        // 设置对话框全屏
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
        }
    }

    /**
     * 在 DialogFragment 显示时暂停首页视频
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mainActivity != null) {
            mainActivity.pauseHomePageVideos();
        }
    }

    /**
     * 在 DialogFragment 关闭时恢复首页视频
     */
    @Override
    public void dismiss() {
        // 先暂停所有视频
        if (recyclerView != null) {
            for (int i = 0; i < recyclerView.getChildCount(); i++) {
                VideoViewHolder holder = (VideoViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                if (holder != null) {
                    holder.release();
                }
            }
        }

        super.dismiss();

        // 恢复首页视频
        if (mainActivity != null) {
            mainActivity.resumeHomePageVideos();
        }
    }

    /**
     * 刷新当前播放器中的视频数据
     */
    public void refreshVideoData() {
        if (videoAdapter != null && !videoList.isEmpty()) {
            new Thread(() -> {
                try {
                    // 重新加载视频数据以确保评论数更新
                    ArrayList<Long> videoIds = new ArrayList<>();
                    for (Video video : videoList) {
                        videoIds.add(video.getId());
                    }

                    List<Video> updatedVideos = loadVideosByIds(videoIds);

                    if (getActivity() != null && !getActivity().isFinishing()) {
                        getActivity().runOnUiThread(() -> {
                            if (isAdded() && videoAdapter != null) {
                                videoAdapter.setVideos(updatedVideos);

                                // 重新绑定当前可见的ViewHolder以确保评论数更新
                                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                                if (layoutManager instanceof LinearLayoutManager) {
                                    int firstVisible = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                                    int lastVisible = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();

                                    for (int i = firstVisible; i <= lastVisible; i++) {
                                        VideoViewHolder holder = (VideoViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                                        if (holder != null) {
                                            Video video = updatedVideos.get(i);
                                            User currentUser = User.getCurrentUser(mainActivity, dbHelper);
                                            if (currentUser != null) {
                                                holder.bind(video, dbHelper, currentUser);
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    // 静默处理异常
                }
            }).start();
        }
    }

    /**
     * 显示作品操作对话框（删除/编辑）
     */
}